# coding:utf-8
__author__ = "chenghao"
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

import urllib2, json
from bottle import Bottle, request

weather_app = Bottle()


@weather_app.get("/")
def index():
	location = request.query.getunicode("location", "")
	if location:
		url = "http://api.map.baidu.com/telematics/v3/weather"
		url_val = "location=" + location + "&output=json&ak=Kva4gmB4sRQKZHypQFG211wV"

		try:
			res_data = urllib2.urlopen(url + "?" + url_val, timeout=30)
			res = res_data.read()
			m = json.loads(res)

			result = {}
			error = m["error"]
			status = m["status"]
			if error == 0 and status == "success":
				result["code"] = 0
				result["date"] = m["date"]
				results = m["results"][0]
				result["cidy_name"] = results["currentCity"]
				result["weather_data"] = results["weather_data"]
				return result
			else:
				return {"code": -20, "msg": "查询数据为空"}
		except Exception, e:
			print e
			return {"code": -10, "msg": "系统异常"}
	else:
		return {"code": -1, "msg": "请输入查询关键字"}
